import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:dbio_utils/generic_filehandle/generic_file_handle.dart';

class LocalFile extends GenericFileHandle {
  File _file;

  LocalFile(File file) {
    _file = file;
  }

  @override
  Future<Uint8List> read(int offset, int length, [int position = 0, String encoding]) async {
    int _length = _file.lengthSync();

    int end = position + length;
    if (end > _length) end = _length;
    print('file length: $_length, position:$position, end:$end, read len:$length');
    _file.openRead(position, end).transform(utf8.decoder);
    return await _file.openRead(position, end).first;

    // RandomAccessFile _randomFile = _file.openSync();
    // int readLength = _randomFile.readIntoSync(buffer, position, end);
    // return buffer.sublist(0, readLength);
  }

  Future<Map> stat() async {
    FileStat stat = await _file.stat();
    return {
      'name': _file.path,
      'lastModified': stat.modified.millisecondsSinceEpoch,
      'lastModifiedDate': stat.modified,
      'size': stat.size,
      'type': stat.type,
    };
  }

  @override
  Future<Uint8List> readFile({String encoding}) async {
    return _file?.readAsBytesSync();
  }

  @override
  int get size => _file?.lengthSync() ?? 0;

  @override
  Future<String> readAsString({Encoding encoding}) async {
    return _file?.readAsStringSync(encoding: encoding);
  }

  @override
  Stream<List<int>> openStream([int start, int end]) {
    return _file.openRead(start, end);
  }
}
